package com.android.aishangauction.fragment.member;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.aishangauction.activity.BaseObject;
import com.android.aishangauction.activity.MainTab;
import com.android.aishangauction.activity.mine.TransparentActivity;
import com.android.aishangauction.adapt.listMineTeamAdapt;
import com.android.aishangauction.model.member.TeamListData;
import com.android.aishangauction.utils.MyLog;
import com.android.aishangauction.utils.ObjectUtils;
import com.android.aishangauction.view.recycleview.CustomLoadMoreView;
import com.android.aishangauction.utils.ConstantsUrl;
import com.android.aishangauction.utils.HttpUtils;
import com.android.aishangauction.R;
import com.android.aishangauction.model.member.TeamListDataCallback;
import com.android.aishangauction.utils.LoginState;
import com.android.aishangauction.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static android.app.Activity.RESULT_OK;

/**
 * 我的团列表
 * ---------------------------------------
 */
public class Fragment_Mine_Team extends BaseFragment implements BaseQuickAdapter.RequestLoadMoreListener {


    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    private View rootView;
    private static final String ARG_PARAM1 = "param1";
    private String mParam1;
    //控件是否已经初始化
    private boolean isPrepared;
    private listMineTeamAdapt adapter;
    private int page = 1;
    private boolean networkConnected;
    private FragmentActivity mcontext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
    }

    public static Fragment_Mine_Team newInstance(String param1) {
        Fragment_Mine_Team fragment = new Fragment_Mine_Team();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == TO_REPLY) {

//            progress.setVisibility(View.VISIBLE);
            mRecyclerView.scrollToPosition(0);
            page = 1;
            pos = position;
            GetDataListData(page, mParam1);

            ((MainTab) mcontext).isupdate = true;
        }


    }

    private static final int TO_REPLY = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_recycle_refresh, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        mainTopBg.setVisibility(View.GONE);
        initUI();
        isPrepared = true;
        setlazyLoad();
        return rootView;
    }

    private int pos = -1;
    private int Current_page = 1;
    private int position;

    private void initUI() {
        adapter = new listMineTeamAdapt(R.layout.item_list_mine_team, null);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                Intent intent = new Intent(mcontext, BaseObject.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "订单详情");
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, adapter.getItem(position).getOrder_sn());
                mcontext.startActivity(intent);
            }
        });

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, final int position) {
                switch (view.getId()) {
                    case R.id.item_list_mine_tuan_invaite:
                    case R.id.item_list_mine_tuan_pintuandetail:
                        Intent intent_tuan = new Intent(mcontext, BaseObject.class);
                        intent_tuan.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "团详情");
                        intent_tuan.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, adapter.getItem(position).getCommon_id());
                        startActivity(intent_tuan);
                        break;
                    case R.id.item_list_mine_tuan_dingdangdetail:
                        Intent intent = new Intent(mcontext, BaseObject.class);
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "订单详情");
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, adapter.getItem(position).getOrder_sn());
                        startActivity(intent);
                        break;
                    case R.id.item_list_mine_tuan_update:
                        Fragment_Mine_Team.this.position = position;
                        Intent share = new Intent(mcontext, TransparentActivity.class);
                        share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 2);
                        share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_TEAMS_ID, adapter.getItem(position).getId());
                        share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_TEAMS_THUMB, adapter.getItem(position).getThumb());
                        share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_TEAMS_TITLE, adapter.getItem(position).getName());
                        share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_TEAMS_NUM, adapter.getItem(position).getTeam_num());
                        startActivityForResult(share, TO_REPLY);
                        break;
                }


                return false;
            }
        });


    }

    @Override
    protected void setlazyLoad() {
        super.setlazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        page = 1;
        mRecyclerView.scrollToPosition(0);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            GetDataListData(page, mParam1);
        } else {

            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }

        //刷新
        ReFreshData();


    }

    private void ReFreshData() {
        //设置颜色
        swipeRefreshLayout.setColorSchemeResources(R.color.app_title);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                networkConnected = ObjectUtils.isNetworkConnected(getActivity());
                if (networkConnected) {

                    page = 1;
                    GetDataListData(page, mParam1);

                } else {

                    ObjectUtils.toast(getActivity(), "网络连接出现异常");
                    swipeRefreshLayout.setRefreshing(false);
                }


            }
        });

    }

    //获取列表数据
    private void GetDataListData(final int page, String type) {


        String address;
        if (type.equals("0")) {
            address = ConstantsUrl.domain + ConstantsUrl.MEMBERTUAN + "?&page=" + page;
        } else {
            address = ConstantsUrl.domain + ConstantsUrl.MEMBERTUAN + "?&page=" + page + "&status=" + type;
        }

        MyLog.e("地址", address);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);

            HttpUtils.get(address, header, null, new TeamListDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    swipeRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(TeamListData response, int id) {
                    swipeRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);


                    if (response.getCode() == 0) {
                        ArrayList<TeamListData.MineTuanData.MineTuandata> listdata = new ArrayList<>();
                        if (response.getData() == null && page == 1) {
                            noData.setVisibility(View.VISIBLE);
                            return;
                        }
                        noData.setVisibility(View.GONE);
                        if (response.getData() != null && response.getData().getList().size() > 0) {
                            listdata.addAll(response.getData().getList());
                            if (page == 1) {
                                adapter.setNewData(listdata);
                            } else {
                                adapter.addData(listdata);
                                adapter.loadMoreComplete();
                            }
                            if (pos > -1) {
                                adapter.setData(pos, response.getData().getList().get(pos));
                            }
                        } else {
                            adapter.loadMoreEnd();
                        }


                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                        noDataTv.setVisibility(View.VISIBLE);
                    }

                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }


    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        page = 1;
        GetDataListData(page, mParam1);
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetDataListData(page, mParam1);
    }
}
